<template>
  <div class="form-container">
    <el-row type="flex" justify="center">
      <el-form style="width:100%;" ref="form" :model="form" :rules="formRules" label-position="left" label-width="80px">
        <!-- 用户手机号 -->
        <el-row v-if="!isUpdateUser()" type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('user.tel')" prop="tel">
              <el-input v-model="form.tel" :placeholder="$t('input')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 用户名称 -->
        <el-row type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('user.name')" prop="name">
              <el-input v-model="form.name" :placeholder="$t('input')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 密码 -->
        <el-row v-if="!isUpdateUser()" type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('login.password')" prop="password">
              <el-input type="password" auto-complete="off" v-model="form.password" :placeholder="$t('input')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 确认密码 -->
        <el-row v-if="!isUpdateUser()" type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('login.confirmPasswordPlaceHolder')" prop="password_confirmation">
              <el-input type="password" auto-complete="off" v-model="form.password_confirmation" :placeholder="$t('input')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 角色 -->
        <el-row type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item 
              :label="$t('user.role')" 
              prop="roles">
              <el-select style="width: 100%;"
                v-model="form.roles" 
                multiple 
                name="roles" 
                :placeholder="$t('select')">
                <el-option v-for="role in allRoles" :label="role.name" :value="role.role_id" :key="role.role_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 验证码 -->
        <el-row v-if="!isUpdateUser()" type="flex" justify="center">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item 
              :label="$t('login.validationCode')"
              prop="code">
              <el-input 
                v-model="form.code"
                name="code" 
                type="text"
                auto-complete="off"
                :placeholder="$t('login.validationCodePlaceHolder')"
                class="sms-code-input"></el-input>
              <el-button 
                :loading="smsCodeLoading" 
                type="primary" 
                class="sms-code-button" 
                @click.native.prevent="handleSmsCodeRequest" 
                :disabled="smsCodeDownCount !== 0">
                {{ getSmsCodeButtonText }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 提交 -->
        <el-row type="flex" justify="center">
          <el-button :loading="submitLoading" type="primary" @click.native.prevent="onSubmit">{{$t('submit')}}</el-button>
        </el-row>
      </el-form>
    </el-row>
  </div>
</template>

<script>
import _ from 'lodash'
import { isvalidPhone, validateConfirmPassword,  } from "@/utils/validate"

export default {
  name: 'UserForm',
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!isvalidPhone(value)) {
        callback(new Error(this.$t("login.phoneValidationTips")));
      } else {
        callback();
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error(this.$t("login.passwordValidationTips")));
      } else {
        callback();
      }
    };
    const validateConfirmPass = (rule, value, callback) => {
      if (!validateConfirmPassword(this.form.password, value)) {
        callback(new Error(this.$t("login.confirmPasswordValidationTips")));
      } else {
        callback();
      }
    }
    return {
      form: {
        tel: '',
        name: '',
        password: '',
        password_confirmation: '',
        roles: [],
        code: '',
      },
      // form 校验规则
      formRules: {
        name: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }],
        tel: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }, {
          validator: validatePhone,
          trigger: ['blur', 'change'],
        }],
        password: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }, {
          validator: validatePass,
          trigger: 'blur'
        }],
        password_confirmation: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }, {
          validator: validateConfirmPass,
          trigger: 'blur'
        }],
        roles: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }],
        code: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }]
      },
      // 编辑中的用户id
      userID: this.$route.query.userID,
      // 编辑中的用户对象
      user: null,
      // 组件中的loading遮罩层对象，调用openFullScreenLoading方法时赋值
      loading: null,
      submitLoading: false,
      // 短信验证码加载中标志位
      smsCodeLoading: false,
      // 短信验证码倒数秒数
      smsCodeDownCount: 0,
      // 所有角色
      allRoles: []
    }
  },
  created: function() {
    this.init()
  },
  computed: {
    getSmsCodeButtonText() {
      if (this.smsCodeDownCount > 0) {
        return this.$t("login.smsCodeWaitTips", {
          second: this.smsCodeDownCount
        });
      } else {
        return this.$t("login.getValidationCode");
      }
    }
  },
  methods: {
    /**
     * 组件初始化方法
     */
    init() {
      this.initForm()

      this.initEditUser()
    },
    onSubmit() {
      this.$message('submit!')
      this.$refs.form.validate(valid => {
        if (valid) {
          this.addOrUpdateUser()
        }
      })
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    },
    /**
     * 调用api，获取短信验证码
     */
    handleSmsCodeRequest() {
      this.smsCodeLoading = true;
      this.smsCodeDownCount = 60;
      const timmerId = setInterval(() => {
        this.smsCodeDownCount--;
        if (this.smsCodeDownCount <= 0) {
          if (timmerId) {
            clearInterval(timmerId);
          }
        }
      }, 1000);
      this.smsCodeLoading = false;
    },
    /**
     * 编辑用户初始化
     */
    initEditUser() {
      this.openFullScreenLoading()

      const promises = []
      if (this.userID) {
        promises.push(this.getUserDetailByID(this.userID))
        promises.push(this.getAllRoleList())
      } else {
        promises.push(this.getAllRoleList())
      }
      Promise.all(promises).then(datas => {
        if (Array.isArray(datas)) {
          if (datas.length === 2) {
            this.processUserData(datas[0])
            this.processRoleData(datas[1])
          } else if (datas.length === 1) {
            this.processRoleData(datas[0])
          }
        }

        this.closeFullScreenLoading()
      }).catch(error => {
        this.closeFullScreenLoading()

        console.error('init edit user has error:', error)
        this.$notify.error({
          title: this.$t('operationFailed'),
          message: this.$t('errorTips'),
        })
      }) 
    },
    /**
     * form 字段初始化
     */
    initForm() {
      if (this.isUpdateUser()) {
        this.formRules = _.omit(this.formRules, ['code', 'password', 'password_confirmation', 'tel'])
        this.form = _.omit(this.form, ['code', 'password', 'password_confirmation', 'tel'])
      }
    },
    /**调用api，提交或更新用户 */
    addOrUpdateUser() {
      this.submitLoading = true
      let promise
      
      if (this.userID) {
        // 更新角色需要带id
        this.form.admin_id = this.userID
        promise = this.$store
          .dispatch('updateOneUser', this.form)
      } else {
        promise = this.$store
          .dispatch('addOneUser', this.form)
      }
      
      if (promise) {
        promise.then(data => {
          this.submitLoading = false;
          
          if (data && data['code'] === 0) {
            this.$notify({
              title: this.$t('operationSuccess'),
              message: data['msg'],
              type: 'success'
            })
          } else {
            this.$notify({
              title: this.$t('operationFailed'),
              message: data['msg'],
              type: 'warning'
            })
          }

          this.goToUserManagement()
        }).catch((error) => {
          console.error('add or update user has error:', error)
          this.submitLoading = false;
          let msg = this.$t('errorTips')
          if (error && error['code'] !== 0) {
            msg = error['msg']
          }
          this.$notify.error({
            title: this.$t('operationFailed'),
            message: msg,
          })
        })
      }
    },
    /**
     * 调用api，获取所有权限
     */
    getAllRoleList() {
      return this.$store
        .dispatch('getRoleList')
    },
    /**
     * 处理角色数据
     */
    processRoleData(data) {
      if (data && data['code'] === 0) {
        const roleDatas = data['data']['data']

        this.allRoles = roleDatas
      } else {
        this.$notify({
          title: this.$t('operationFailed'),
          message: data['msg'],
          type: 'warning'
        })
      }
    },
    /**
     * 调用api，获取用户详情 
     */
    getUserDetailByID(id) {
      return this.$store.dispatch('getUserByID', { id: this.userID })
    },
    /**
     * 处理用户详情数据
     */
    processUserData(data) {
      if (data && data['code'] === 0) {
        this.user = data['data']

        // 初始化form的值
        const { tel, name, roles } = this.user
        // this.form.tel = tel
        this.form.name = name
        if (_.isArray(roles) && roles.length > 0) {
          this.form.roles = roles.map(item => {
            if (_.isObject(item)) {
              return item.role_id
            } else {
              return item
            }
          })
        }
        
      } else {
        this.$notify({
          title: this.$t('operationFailed'),
          message: data['msg'],
          type: 'warning'
        })
      }
    },
    /**
     * 当前是否更新用户操作
     * 是则返回true
     */
    isUpdateUser() {
      let result = false
      const routerPath = this.$route.path
      if (routerPath.includes('editUser') && this.userID) {
        result = true
      }
      return result
    },
    /**
     * 跳转到用户管理页面
     */
    goToUserManagement() {
      this.$router.push({ path: '/user' })
    },
    /**
     * 显示loading遮罩层
     */
    openFullScreenLoading() {
      this.loading = this.$loading({
        lock: true,
        text: this.$t('loading') + '...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    /**
     * 关闭loading遮罩层
     */
    closeFullScreenLoading() {
      if (this.loading) {
        this.loading.close()
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "@/styles/variables.scss";
@import "../../styles/form-public";
.form-container {
  max-width: 700px;
  .sms-code-input {
    width: 57%;
    // padding: 12px 7px;
  }
  .sms-code-button {
    padding: 12px 7px;
  }
}
</style>

